<template>
  <panel title="物流信息录入">
    <el-form class="form-horizontal" :model="logisticsDto" :rules="logisticsRules" label-width="150px"
             ref="logisticsForm">
      <el-form-item label="返还客户日期" prop="backTime">
        <el-input v-model="formatterBackTime" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="物流公司名称" prop="logisticsCompany">
        <el-select v-model="logisticsDto.logisticsCompany"
                   placeholder="请选择物流公司"
                   prop="logisticsCompany"
                   :filterable="true"
                   :clearable="true"
                    @change="onSelect">
          <el-option
            v-for="item1 in logisticsCompanyList"
            :key="item1.id"
            :label="item1.name"
            :value="item1.id">
          </el-option>
        </el-select>
        <!--<el-input v-model="logisticsDto.logisticsCompany" auto-complete="off"></el-input>-->
      </el-form-item>
      <el-form-item label="快递单号" prop="logisticsNumber">
        <el-input v-model="logisticsDto.logisticsNumber" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="客户姓名">
        <el-input v-model="logisticsDto.customerName" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="客户地址">
        <el-input v-model="logisticsDto.customerAddress" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="客户联系电话">
        <el-input v-model="logisticsDto.customerTel" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="exportLoading" @click="printFactoryReturnOrder()" v-no-more-click>打印返还通知单
        </el-button>
        <!--v-no-more-click为防止重复提交指令-->
        <el-button type="primary" @click="onBtnFinishWorkOrder()" style="float: right;" v-no-more-click>工单完结
        </el-button>
      </el-form-item>
    </el-form>
  </panel>
</template>

<script>
  import Panel from '@/components/common/Panel'
  import { parseTime } from '@/utils'
  import { apiGetLogisticInfo, apiPostFactoryReturn, apiPrintFactoryReturnOrder } from '@/api/repairs/factory/index'
  import { apiGetLogisticsCompanyList } from '@/api/dictionary'
  import { apiGetUserById } from '@/api/basic/account'
  import {getName, getFactoryId} from '@/utils/token'
  import {downloadExcel} from "../../utils";

  export default {
    components: {
      Panel
    },
    computed: {
      formatterBackTime () {
        return parseTime(this.logisticsDto.backTime, '{y}-{m}-{d}')
      }
    },
    created () {
      this.logisticsDto.ids = this.$route.query.ids
      this.apiGetLogisticInfo()
      this.selectedLogisticsCompanyInit()
    },
    data () {
      return {
        customer: {
          id: undefined,
          name: '',
          address: '',
          tel: ''
        },
        logisticsCompanyList: [],
        logisticsDto: {
          ids: [],
          backTime: new Date().getTime(),
          logisticsNumber: '',
          logisticsCompany: '',
          logisticsCompanyName: '',
          customerName: '',
          province: '',
          provinceCode: '',
          city: '',
          cityCode: '',
          customerTel: '',
          customerAddress: '',
          operator: '',
          factoryId: getFactoryId(),
          batch: this.$route.query.batch
        },
        logisticsRules: {
          logisticsCompany: [
            {required: true, message: '请填写物流公司名', trigger: 'blur'}
          ],
          logisticsNumber: [
            {required: true, message: '请填写物流单号', trigger: 'blur'},
            {max: 255, message: '长度不超过 255 个字符', trigger: 'blur'}
          ]
        },
        batch: this.$route.query.batch,
        userId: this.$route.query.userId,
        type: this.$route.query.type,
        exportLoading: false
      }
    },
    methods: {
      selectedLogisticsCompanyInit () {
        apiGetLogisticsCompanyList().then(response => {
          let logisticsCompanyList = response.data
          let logisticsCompany = []
          let temp = {}
          for (let i in logisticsCompanyList) {
            if (!temp[logisticsCompanyList[i].name]) {
              temp[logisticsCompanyList[i].name] = logisticsCompanyList[i].id
            }
          }
          for (let k in temp) {
            logisticsCompany.push({'name': k, 'id': temp[k]})
          }
          this.logisticsCompanyList = logisticsCompany
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      apiGetLogisticInfo () {
        if (this.type === 0) {
          apiGetLogisticInfo(this.batch).then(response => {
            let logistic = response.data
            this.logisticsDto.customerName = logistic.contact
            this.logisticsDto.province = logistic.province
            this.logisticsDto.provinceCode = logistic.provinceCode
            this.logisticsDto.city = logistic.city
            this.logisticsDto.cityCode = logistic.cityCode
            this.logisticsDto.customerTel = logistic.tel
            this.logisticsDto.customerAddress = logistic.address
          }).catch(() => {
            this.tableLoadingFlag = false
          })
        } else if (this.type === 1) {
          apiGetUserById(this.userId).then(response => {
            let rsp = response.data
            this.logisticsDto.customerName = rsp.name
            this.logisticsDto.province = rsp.province
            this.logisticsDto.provinceCode = rsp.provinceCode
            this.logisticsDto.city = rsp.city
            this.logisticsDto.cityCode = rsp.cityCode
            this.logisticsDto.customerTel = rsp.tel
            this.logisticsDto.customerAddress = rsp.address
          })
        }
      },
      // 获取下拉框中的label值(物流公司名称)
      onSelect (val) {
        let obj = this.logisticsCompanyList.find((item1) => {
          return item1.id === val
        })
        this.logisticsDto.logisticsCompanyName = obj.name
      },
      // 打印工厂返还通知单
      printFactoryReturnOrder () {
        if (this.logisticsDto.logisticsCompany === '' || this.logisticsDto.logisticsCompany === null) {
          this.$message({
            showClose: true,
            message: '请选择物流公司',
            type: 'error'
          })
        } else if (this.logisticsDto.logisticsNumber === '' || this.logisticsDto.logisticsNumber === null) {
          this.$message({
            showClose: true,
            message: '请填写物流单号',
            type: 'error'
          })
        } else {
          this.exportLoading = true
          apiPrintFactoryReturnOrder(this.logisticsDto).then(response => {
            downloadExcel(response.data, '自有售后工厂返还通知单')
            this.exportLoading = false
          }).catch(() => {
            this.exportLoading = false
          })
        }
      },
      onBtnFinishWorkOrder () {
        this.$refs['logisticsForm'].validate((valid) => {
          if (valid) {
            this.logisticsDto.operator = getName()
            apiPostFactoryReturn(this.logisticsDto).then(() => {
              this.$message({
                showClose: true,
                message: '提交成功',
                type: 'success'
              })
              this.$router.push({
                path: '/repairs/factory/return'
              })
            }).catch(() => {
              this.tableLoadingFlag = false
            })
          } else {
            return false
          }
        })
      }
    }
  }
</script>
